﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class IfengLogin : LoginImplBase
    {
        public IfengLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://play.ifeng.com/?_a=dologin";
            string data = String.Format("username={0}&password={1}&reurl=&game=&area=", _username, _password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            // 302 to play.ifeng.com
            string location = resp.getExtraHeader("Location");
            if (location == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string redirecturl = String.Format("http://play.ifeng.com/?_a=entergame&game=astd&area={0}", _acc.ServerId);
            // 302 to http://play.ifeng.com/?_c=astd&_a=enterGame&area=21
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            if (resp.StatusCode == 302)
            {
                location = resp.getExtraHeader("Location");
                makeSureValidUri(redirecturl, ref location);
                resp = TransferMgr.doGetPure(location, ref cookies);
                if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

                string content = resp.getContent();
                Regex re = new Regex("\\(\"#game_iframe_id\"\\)\\.attr\\(\"src\",\"([^\"']*?)\"");
                Match m = re.Match(content);
                if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

                string gameurl = m.Groups[1].Value;
                processStartGame(gameurl, result, ref cookies);
            }
            else
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
            }
            return result;
        }
    }
}
